package me.mouse.Lottery;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import net.milkbowl.vault.economy.Economy;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;

public class Lottery extends JavaPlugin {
	
	private static List<LotteryMachine> machine = Collections.synchronizedList(new ArrayList<LotteryMachine>());
	public static Economy economy = null;
	public static boolean loadEco = false;
	private static Map<Player, LotteryMachine> cache = new ConcurrentHashMap<>();
	
	private static File pluginFile;

	private boolean setupEconomy() {
		RegisteredServiceProvider<Economy> economyProvider = getServer()
				.getServicesManager().getRegistration(
						net.milkbowl.vault.economy.Economy.class);
		if (economyProvider != null) {
			economy = economyProvider.getProvider();
		}

		return (economy != null);
	}

	@Override
	public void onEnable() {
		pluginFile = getDataFolder();
		
		if (setupEconomy()) {
			getLogger().info("已找到Vault");
			loadEco = true;
		} else {
			getLogger().info("未找到Vault");
			loadEco = false;
		}

		saveDefaultConfig();
		loadLotteryMachine();
		getServer().getPluginManager().registerEvents(new LotteryListener(),
				this);
		getLogger().info("Lottery v1.0.3 启动成功");
	}

	@Override
	public void onDisable() {
		getLogger().info("Lottery v1.0.3 关闭成功");
	}

	@SuppressWarnings("deprecation")
	@Override
	public boolean onCommand(CommandSender sender, Command command,
			String label, String[] args) {
		if (label.equalsIgnoreCase("lottery") || command.equals("l")) {
			if (sender instanceof Player) {
				if (sender.hasPermission("lottery.use") || sender.isOp()) {
					if (args.length == 0 || args[0].equalsIgnoreCase("help")
							|| args[0].equalsIgnoreCase("h")) {
						sender.sendMessage("§a-------抽奖指令帮助-------");
						sender.sendMessage("§6/lottery help - 查看指令帮助");
						sender.sendMessage("§6/lottery list - 查看抽奖机列表");
						sender.sendMessage("§6/lottery info <名称> - 查看抽奖机信息");
						sender.sendMessage("§6/lottery start <名称> - 开始抽奖");
						sender.sendMessage("§c--------管理员指令--------");
						sender.sendMessage("§6/lottery admin create <名称> - 创建一个新的抽奖机");
						sender.sendMessage("§6/lottery admin edit <名称> - 编辑一个抽奖机");
						sender.sendMessage("§6/lottery admin remove <名称> - 删除一个抽奖机");
						sender.sendMessage("§6/lottery admin save - 保存正在编辑中的抽奖机");
						sender.sendMessage("§6/lottery admin setinfo <信息> - 设置抽奖机的介绍");
						sender.sendMessage("§6/lottery admin setprice <价格> - 设置抽奖机一次抽奖的价格");
						sender.sendMessage("§6/lottery admin add <抽到的几率> - 添加手上的物品到抽奖机内");
						sender.sendMessage("§6/lottery admin del <物品编号> - 删除一个物品");
						sender.sendMessage("§6--------------------------");
						return true;
					}
					if (args[0].equalsIgnoreCase("list")
							|| args[0].equalsIgnoreCase("l")) {
						sender.sendMessage("§a获取所有的抽奖机:");
						for (LotteryMachine lm : machine) {
							sender.sendMessage("§6 - " + lm.getName());
						}
						sender.sendMessage("§a------------------------");
						return true;
					}
					if (args[0].equalsIgnoreCase("info")
							|| args[0].equalsIgnoreCase("i")) {
						if (args.length < 2) {
							sender.sendMessage("§c参数不足!");
							return true;
						}
						LotteryMachine lm = getLotteryMachine(args[1]);
						if (lm == null) {
							sender.sendMessage("§c不存在此抽奖机");
							return true;
						}
						sender.sendMessage("§6--------抽奖机信息--------");
						sender.sendMessage("§6名称: " + lm.getName());
						sender.sendMessage("§6简介: " + lm.getInfo());
						sender.sendMessage("§6价格: " + lm.getPrice());
						sender.sendMessage("§6物品列表:");
						for (ItemStack item : lm.getAllItem()) {
							sender.sendMessage("§6  - "
									+ item.getType().toString() + "("
									+ item.getType().getId() + ":"
									+ item.getDurability() + "):"
									+ item.getAmount());
						}
						sender.sendMessage("§6---------------------------");
						return true;
					}
					if (args[0].equalsIgnoreCase("start")) {
						if (args.length < 2) {
							sender.sendMessage("§c参数不足!");
							return true;
						}
						LotteryMachine lm = getLotteryMachine(args[1]);
						if (lm == null) {
							sender.sendMessage("§c不存在此抽奖机!");
							return true;
						}
						if (!loadEco) {
							sender.sendMessage("§c未找到Vault!");
							return true;
						}
						if (!sender.hasPermission("lottery.machine."+ lm.getName())) {
							sender.sendMessage("§c你没有使用这个抽奖机的权限!");
							return true;
						}
						if (economy.withdrawPlayer((Player)sender,
								lm.getPrice()).transactionSuccess()) {
							ItemStack item = lm.getRandomItem();
							Player player = (Player) sender;
							player.getInventory().addItem(item);
							sender.sendMessage("§a抽到物品: §e"
									+ item.getType().toString() + "("
									+ item.getType().getId() + ":"
									+ item.getDurability() + "):"
									+ item.getAmount());
							return true;
						} else {
							sender.sendMessage("§c资金不足!");
							return true;
						}
					}
				}
				if (args[0].equalsIgnoreCase("admin")) {
					if (sender.isOp() || sender.hasPermission("lottery.admin")) {
						if (args[1].equalsIgnoreCase("create")
								|| args[1].equalsIgnoreCase("c")) {
							if (args.length < 3) {
								sender.sendMessage("§c参数不足!");
								return true;
							}
							if (getLotteryMachine(args[2]) != null) {
								sender.sendMessage("§c已有重名抽奖机存在!");
								return true;
							}
							cache.remove((Player) sender);
							cache.put((Player) sender, new LotteryMachine(
									args[2]));
							sender.sendMessage("§a成功创建新的抽奖机: §e" + args[2]);
							return true;
						}
						if (args[1].equalsIgnoreCase("save")
								|| args[1].equalsIgnoreCase("s")) {
							LotteryMachine lm = cache.get((Player) sender);
							if (lm == null) {
								sender.sendMessage("§c不存在编辑中的抽奖机!");
								return true;
							}
							lm.save();
							machine.add(cache.get((Player) sender));
							cache.remove((Player) sender);
							sender.sendMessage("§a成功保存抽奖机: §e" + lm.getName());
							return true;
						}
						if (args[1].equalsIgnoreCase("setinfo")
								|| args[1].equalsIgnoreCase("si")) {
							if (args.length < 3) {
								sender.sendMessage("§c参数不足!");
								return true;
							}
							LotteryMachine lm = cache.get((Player) sender);
							lm.setInfo(args[2]);
							sender.sendMessage("§a成功设置抽奖机的介绍为: §e" + args[2]);
							return true;
						}
						if (args[1].equalsIgnoreCase("edit")
								|| args[1].equalsIgnoreCase("e")) {
							if (args.length < 3) {
								sender.sendMessage("§c参数不足!");
								return true;
							}
							LotteryMachine lm = getLotteryMachine(args[2]);
							if (lm == null) {
								sender.sendMessage("§c不存在这个抽奖机");
								return true;
							}
							cache.put((Player) sender, lm);
							machine.remove(lm);
							sender.sendMessage("§a开始编辑抽奖机: §e" + lm.getName());
							return true;
						}
						if (args[1].equalsIgnoreCase("remove")
								|| args[1].equalsIgnoreCase("r")) {
							if (args.length < 3) {
								sender.sendMessage("§c参数不足!");
								return true;
							}
							LotteryMachine lm = getLotteryMachine(args[2]);
							if (lm == null) {
								sender.sendMessage("§c不存在这个抽奖机");
								return true;
							}
							machine.remove(lm);
							lm.remove();
							sender.sendMessage("§a已移除抽奖机: §e" + lm.getName());
							return true;
						}
						if (args[1].equalsIgnoreCase("setprice")
								|| args[1].equalsIgnoreCase("sp")) {
							if (args.length < 3) {
								sender.sendMessage("§c参数不足!");
								return true;
							}
							LotteryMachine lm = cache.get((Player) sender);
							if (lm == null) {
								sender.sendMessage("§c不存在编辑中的抽奖机!");
								return true;
							}
							lm.setPrice(Double.valueOf(args[2]));
							sender.sendMessage("§a设置抽奖机的价格为: §e" + args[2]);
							return true;
						}
						if (args[1].equalsIgnoreCase("add")
								|| args[1].equalsIgnoreCase("a")) {
							if (args.length < 3) {
								sender.sendMessage("§c参数不足!");
								return true;
							}
							ItemStack item = ((Player) sender).getItemInHand();
							int chance = Integer.valueOf(args[2]);
							LotteryMachine lm = cache.get((Player) sender);
							if (lm == null) {
								sender.sendMessage("§c不存在编辑中的抽奖机!");
								return true;
							}
							lm.addItem(item, chance);
							sender.sendMessage("§a已将物品: §f"
									+ item.getType().toString() + "("
									+ item.getType().getId() + ":"
									+ item.getDurability() + "):"
									+ item.getAmount() + " §a添加,几率为: §e"
									+ args[2]);
							return true;
						}
						if (args[1].equalsIgnoreCase("del")
								|| args[1].equalsIgnoreCase("d")) {
							if (args.length < 3) {
								sender.sendMessage("§c参数不足!");
								return true;
							}
							int number = Integer.valueOf(args[2]);
							LotteryMachine lm = cache.get((Player) sender);
							if (lm == null) {
								sender.sendMessage("§c不存在编辑中的抽奖机!");
								return true;
							}
							lm.removeItem(number);
							sender.sendMessage("§a已将编号为: §e" + args[2]
									+ " §a的物品移除");
							return true;
						}
						if (args[1].equalsIgnoreCase("reload")) {
							reloadConfig();
							loadLotteryMachine();
							sender.sendMessage("§a重载成功!");
							return true;
						}
						sender.sendMessage("§c未知的指令!");
						return true;
					}
					sender.sendMessage("§c权限不足!");
					return true;
				}
				sender.sendMessage("§c权限不足!");
				return true;
			}
			sender.sendMessage("§c未知的指令!");
			return true;
		}
		return true;
	}

	public void loadLotteryMachine() {
		machine.clear();
		FileConfiguration file = load("machine.yml");
		Set<String> lms = file.getConfigurationSection("").getKeys(false);
		if (lms.size() <= 0) {
			return;
		}
		for (String s: lms) {
			LotteryMachine lm = new LotteryMachine(s);
			lm.setInfo(file.getString(s + ".info", "§f暂无介绍"));
			lm.setPrice(file.getDouble(s + ".price"));
			Set<String> lmitems = file.getConfigurationSection(s + ".item")
					.getKeys(false);
			if (lmitems.size() > 0) {
				for (int si = 1;lmitems.size()+1>si;si++) {
					lm.addItem(file.getItemStack(s + ".item." + si + ".item"),
							file.getInt(s + ".item." + si + ".chance"));
				}
			}
			machine.add(lm);
		}
	}

	public static LotteryMachine getLotteryMachine(String Name) {
		for (LotteryMachine lm : machine) {
			if (Name.equalsIgnoreCase(lm.getName())) {
				return lm;
			}
		}
		return null;
	}

	public static FileConfiguration load(String name) {
		File file = new File(pluginFile, name);
		if (!file.exists()) {
			if (!file.getParentFile().exists())
				file.getParentFile().mkdirs();
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return YamlConfiguration.loadConfiguration(file);
	}

	public static void save(FileConfiguration file, String name) {
		try {
			file.save(new File(pluginFile, name));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// public boolean openMenu(final Player player,String name){
	// if (player == null) {
	// return false;
	// }
	// LotteryMachine lm = getLotteryMachine(name);
	// if (lm == null){
	// return false;
	// }
	// menu.put(player, lm);
	// ItemStack glass = new ItemStack(Material.STAINED_GLASS_PANE);
	// glass.setDurability((short)8);
	// ItemStack button = new ItemStack(Material.STAINED_GLASS_PANE);
	// glass.setDurability((short)1);
	// ItemMeta mbutton= button.getItemMeta();
	// mbutton.setDisplayName(lm.getName());
	// ArrayList<String> mblore = new ArrayList<>();
	// mblore.add("§e"+lm.getInfo());
	// mblore.add("§e价格为: "+lm.getPrice());
	// mbutton.setLore(mblore);
	// button.setItemMeta(mbutton);
	// final Inventory inv = Bukkit.createInventory(null,InventoryType.DROPPER);
	// inv.addItem(glass,glass,glass,glass,lm.getRandomItem(),glass,glass,button,glass);
	// Bukkit.getScheduler().scheduleSyncDelayedTask(plugin,
	// new Runnable() {
	// public void run() {
	// player.openInventory(inv);
	// }
	// }, 1L);
	// return true;
	// }
}

//更新日志
//1.修复Reload无法清理抽奖机完全
//2.添加牌子抽奖系统[未完成]
